﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace MathBox
{
    class MathBox
    {
        public MathBox()
        {

        }

        public void test()
        {

            Random rd = new Random();
            float f1 = rd.Next(10000) * 0.001f;
            float f2 = GetSignificantFigures(f1,1 ,true);
            f2 = GetSignificantFigures(88888, 0, true);
            f2 = GetSignificantFigures(45.123456f, 5, true);
            string tmp = f2.ToString();
        }

        /// <summary>
        /// 取n位有效数字，无四舍五入
        /// </summary>
        /// <param name="data">原始数据</param>
        /// <param name="n">有效数字位数</param>
        /// <param name="isRound">是否四舍五入</param>
        /// <returns>处理结果</returns>
        public float GetSignificantFigures(float data, int n, bool isRound)
        {
            if (n < 1)
            {
                return 0;
            }
            if (n > 7)//float最多7位有效数字
            {
                return data;
            }
            if (data == 0)
            {
                return 0;
            }
            if (float.IsNaN(data) || float.IsInfinity(data))
            {
                return 0;
            }
            
            string sciString = data.ToString("e");
            int indexE = sciString.IndexOf("e");
            string significantString = sciString.Substring(0, indexE);
            string eString = sciString.Substring(indexE, sciString.Length - indexE);
            
            if (isRound)
            {
                significantString = float.Parse(significantString).ToString("f" + (n - 1).ToString());
            }
            else
            {
                significantString = significantString.Substring(0, n + 1);
            }
            string rstString = significantString + eString;
            float rst = float.Parse(rstString);

            return rst;
        }
    }
}
